package a2023.a1019;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lenovo
 * @date 2023/10/19
 */
public class a {
    public static void main(String[] args) {
        System.out.println(tupleSameProduct(
                new int[]{1, 2, 4, 5, 10}));
    }

    public static int tupleSameProduct(int[] nums) {
        int n = 0;
        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
        int left = 0;
        int right = 1;
        int len = nums.length - 1;
        while (left < len) {
            int num = nums[left] * nums[right];
            if (m.containsKey(num)) {
                m.replace(num, m.get(num) + 1);
            } else {
                m.put(num, 0);
            }
            if (right == len) {
                left++;
                right = left + 1;
            } else {
                right++;
            }
        }

        for (Integer value : m.values()) {
            n += value * (value + 1) / 2;
        }
        return n * 8;
    }

    public int tupleSameProduct2(int[] nums) {
        if (nums == null || nums.length < 4) {
            return 0;
        }
        //缓存所有数组的乘积和相同的次数
        int length = nums.length;
        Map<Integer, Integer> cache = new HashMap<>(length * (length - 1));
        int result = 0;
        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                int num = nums[i] * nums[j];
                Integer count = cache.getOrDefault(num, 0) + 1;
                //说明有相同的乘积
                if (count > 1) {
                    result += (count - 1) * 8;
                }
                cache.put(num, count);
            }
        }
        return result;
    }
}
